package simi;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionOutputServlet extends HttpServlet { 

	private static final String NO_CHANGE = "NO_CHANGE";
	private static final String OLD_OUTPUT = "OLD_OUTPUT";

	/**
	 * Need a UID to extend HttpServlet
	 */
	private static final long serialVersionUID = 1234234238L;
	private static int CHAR_LIMIT = 
		SimiPropertyManager.getConfig().getInt("connection.outputCharLimit");
					
	public void doGet(HttpServletRequest req, HttpServletResponse res) 
		throws ServletException, IOException { 
			
		boolean outputUpdated = false;	
		ByteArrayOutputStream theOutput = 
			(ByteArrayOutputStream)req.getSession().getAttribute
				(Constants.RUNNING_OUTPUT_PARAM);
		String theString = theOutput.toString();
		
		theString = SimiUtils.fixROutput(theString);

		if(theString != null && theString.length() > CHAR_LIMIT){
			theString = theString.substring
				(theString.length() - CHAR_LIMIT, theString.length());
		}

		String oldOutput = (String)req.getSession().getAttribute(OLD_OUTPUT);
		if(oldOutput == null || !oldOutput.equals(theString)){
			outputUpdated = true;
		}
		req.getSession().setAttribute(OLD_OUTPUT, theString);
		res.setContentType("text/plain");
	        res.setHeader("Cache-Control", "no-cache");
        	PrintWriter pw = res.getWriter();
		if(outputUpdated)
        		pw.write(theString);
		else
			pw.write(NO_CHANGE);
        	pw.close();  
	} 
}
